Popular Searches
Popular Course Categories
Popular Courses

Implementing Global Exception Handling with ControllerAdvice

Implementing Global Exception Handling with ControllerAdvice

Spring AOP, Validation, and Exception Management

Implementing Global Exception Handling with @ControllerAdvice in Spring Boot

Course: Advanced Java Training

Topic: Implementing Global Exception Handling with @ControllerAdvice

Course Link: Advanced Java Training at JustAcademy

Demo Link: Register for a Course Demo

Website: Visit JustAcademy


1. Introduction to Exception Handling in Spring Boot

Exception handling is an essential part of Java application development. An exception occurs when an unexpected condition interrupts the normal execution of a program. In a Spring Boot application, exceptions may occur because of invalid user input, missing database records, database connection failures, incorrect request parameters, authentication problems, or unexpected application errors.

Without a proper exception-handling mechanism, applications may return inconsistent responses, expose internal implementation details, or make it difficult for clients to understand what went wrong.

Spring Boot provides the @ControllerAdvice annotation to centralize exception handling across multiple controllers. Developers can define reusable exception-handling methods in one class rather than repeating similar try-catch blocks in every controller.

Learning Objectives

  • Understand exceptions in Java and Spring Boot.
  • Learn the difference between local and global exception handling.
  • Understand the purpose of @ControllerAdvice.
  • Use @ExceptionHandler to handle specific exceptions.
  • Create custom exceptions for business requirements.
  • Return consistent error responses using ResponseEntity.
  • Implement validation error handling.
  • Handle HTTP status codes correctly.
  • Build a centralized exception-handling system for REST APIs.
  • Apply security and debugging best practices.

2. What Is Exception Handling?

Exception handling is the process of detecting and managing errors that occur during program execution. It helps applications respond to unexpected situations in a controlled manner.

2.1 Common Exceptions in Spring Boot

Exception Meaning Example
NullPointerException An operation attempts to use a null reference. Calling a method on a null object.
IllegalArgumentException A method receives an invalid argument. Passing an unsupported value to a method.
MethodArgumentNotValidException Request-body validation fails for a controller argument. A required field is missing or invalid.
HttpMessageNotReadableException The request body cannot be read or converted. Malformed JSON or an incompatible field value.
ResourceNotFoundException A custom exception indicating a missing resource. Looking up an employee that does not exist.
DataAccessException A data-access operation fails. A database operation cannot be completed.
MethodArgumentTypeMismatchException A request parameter cannot be converted to the expected type. Providing text where a numeric ID is required.

2.2 Why Is Exception Handling Important?

  • Prevents uncontrolled error responses.
  • Improves API reliability and maintainability.
  • Provides meaningful feedback to API consumers.
  • Helps developers diagnose application failures.
  • Reduces duplicated exception-handling code.
  • Prevents sensitive implementation details from being exposed.
  • Allows consistent HTTP status codes and error formats.

3. Local Exception Handling vs. Global Exception Handling

3.1 Local Exception Handling

Local exception handling is implemented directly inside an individual controller method. It is useful when a specific endpoint needs custom behavior, but repeating the same handling logic across many controllers can make the application difficult to maintain.

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

    @GetMapping("/employee")
    public ResponseEntity<String> getEmployee() {
        try {
            return ResponseEntity.ok("Employee details retrieved");
        } catch (Exception ex) {
            return ResponseEntity.internalServerError()
                    .body("Something went wrong");
        }
    }
}

This example demonstrates local handling, but catching a broad exception without meaningful recovery or diagnostics is generally not recommended.

3.2 Global Exception Handling

Global exception handling allows developers to define centralized handlers that apply across multiple controllers. Spring's @ControllerAdvice and @RestControllerAdvice annotations are commonly used for this purpose.

Instead of handling the same error in multiple controller methods, a centralized handler can map exceptions to consistent HTTP responses.

Feature Local Handling Global Handling
Location Inside individual controllers. In a dedicated advice class.
Code reuse Limited when repeated across endpoints. High across matching controllers.
Maintenance Can become repetitive. Centralized and easier to update.
Best use Endpoint-specific recovery. Common application-wide error responses.

4. Understanding @ControllerAdvice

@ControllerAdvice is a Spring annotation that enables shared controller-related behavior across multiple controllers. It can be used for global exception handling, model attributes, and binding configuration.

When used with @ExceptionHandler, it allows exception-handling methods to respond to exceptions raised while Spring processes controller requests.

4.1 What Is @RestControllerAdvice?

@RestControllerAdvice combines the behavior of @ControllerAdvice and @ResponseBody. It is especially useful for REST APIs because returned objects are serialized into the response body, commonly as JSON.

For REST API error handling, @RestControllerAdvice is often the simplest choice.

4.2 Difference Between the Annotations

Annotation Purpose
@ControllerAdvice Provides shared controller behavior and supports centralized exception handling.
@RestControllerAdvice Provides shared controller behavior with response-body serialization by default.
@ExceptionHandler Maps selected exception types to handler methods.
@ResponseStatus Associates a specific HTTP status with a handler or exception.
ResponseEntity Allows explicit control over the HTTP response body, headers, and status.

5. Understanding @ExceptionHandler

The @ExceptionHandler annotation identifies a method that handles one or more exception types. The method can be defined in a controller for local handling or in an advice class for shared handling.

5.1 Basic Example

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(
            IllegalArgumentException exception) {

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body("The supplied argument is invalid");
    }
}

Explanation:

  • @RestControllerAdvice registers the class as shared REST controller advice.
  • @ExceptionHandler(IllegalArgumentException.class) identifies the exception type handled by the method.
  • HttpStatus.BAD_REQUEST represents HTTP 400.
  • ResponseEntity defines the response status and body.

The message is intentionally generic so internal implementation details are not exposed to the client.

6. Creating a Standard Error Response

Using a consistent error-response structure helps frontend applications, mobile applications, and API consumers process failures reliably.

6.1 Create an ApiError Class

package com.example.exception;

import java.time.Instant;

public record ApiError(
        Instant timestamp,
        int status,
        String error,
        String message,
        String path
) {}

This example uses a Java record, which requires Java 16 or later. For older Java versions, create a regular class with fields, a constructor, and getters.

6.2 Example JSON Error Response

{
  "timestamp": "2026-10-24T08:30:00Z",
  "status": 404,
  "error": "Not Found",
  "message": "Employee was not found",
  "path": "/api/employees/101"
}

The timestamp and path shown are illustrative. A real response should contain the actual request path and event timestamp. Do not include stack traces, SQL statements, passwords, tokens, or confidential data in client-facing errors.

7. Implementing Global Exception Handling

7.1 Create a Custom ResourceNotFoundException

Custom exceptions represent application-specific error conditions. For example, an employee service can throw a resource-not-found exception when a requested employee does not exist.

package com.example.exception;

public class ResourceNotFoundException
        extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

7.2 Create the Global Exception Handler

package com.example.exception;

import java.time.Instant;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> handleNotFound(
            ResourceNotFoundException exception,
            HttpServletRequest request) {

        ApiError error = new ApiError(
                Instant.now(),
                HttpStatus.NOT_FOUND.value(),
                HttpStatus.NOT_FOUND.getReasonPhrase(),
                exception.getMessage(),
                request.getRequestURI()
        );

        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(error);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiError> handleBadRequest(
            IllegalArgumentException exception,
            HttpServletRequest request) {

        ApiError error = new ApiError(
                Instant.now(),
                HttpStatus.BAD_REQUEST.value(),
                HttpStatus.BAD_REQUEST.getReasonPhrase(),
                "The supplied request is invalid",
                request.getRequestURI()
        );

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(error);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiError> handleUnexpectedException(
            Exception exception,
            HttpServletRequest request) {

        ApiError error = new ApiError(
                Instant.now(),
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),
                "An unexpected error occurred",
                request.getRequestURI()
        );

        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(error);
    }
}

Important: The generic handler is a final fallback for exceptions that reach this advice. More specific handlers should be used for expected errors. In production, log unexpected exceptions with appropriate diagnostic context, but return a safe message to the client. The example uses jakarta.servlet, as in modern Spring Boot applications; older Spring Boot versions may use javax.servlet.

7.3 How the Handler Works

  1. A client sends a request to a controller endpoint.
  2. The controller or service performs the requested operation.
  3. If an exception occurs, normal execution is interrupted.
  4. Spring searches for a matching exception handler.
  5. The global advice creates a standardized error response.
  6. The client receives the response with an appropriate HTTP status code.

8. Handling Exceptions in a REST Controller

The controller can focus on request handling and business-service calls instead of containing repeated error-response logic.

package com.example.controller;

import com.example.exception.ResourceNotFoundException;
import com.example.service.EmployeeService;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/{id}")
    public String getEmployee(@PathVariable Long id) {
        return employeeService.getEmployee(id);
    }
}

The controller delegates the operation to the service. If the service throws ResourceNotFoundException, the global handler processes it.

Example Service

package com.example.service;

import com.example.exception.ResourceNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

    public String getEmployee(Long id) {
        if (id == null || id != 1L) {
            throw new ResourceNotFoundException(
                    "Employee was not found"
            );
        }

        return "Employee details retrieved successfully";
    }
}

This is a simplified demonstration using an in-memory condition. In a real application, the service would retrieve the employee from a repository or database.

9. Handling Request Validation Errors

Spring Boot applications frequently validate incoming request data. Bean Validation annotations such as @NotBlank, @Email, @Min, and @Size help ensure that submitted values meet application requirements.

9.1 Create a Request DTO

package com.example.dto;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class EmployeeRequest {

    @NotBlank(message = "Name is required")
    @Size(max = 100, message = "Name must not exceed 100 characters")
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Email must be valid")
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

For Maven projects, include the Spring Boot validation starter if it is not already present:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

9.2 Validate the Request in a Controller

import com.example.dto.EmployeeRequest;
import jakarta.validation.Valid;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeRegistrationController {

    @PostMapping("/api/employees")
    public String createEmployee(
            @Valid @RequestBody EmployeeRequest request) {

        return "Employee registered successfully";
    }
}

The @Valid annotation triggers validation of the request DTO. In the usual Spring MVC request-body validation flow, validation failures can result in MethodArgumentNotValidException.

9.3 Handle Validation Errors Globally

import java.time.Instant;
import java.util.Map;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(
            MethodArgumentNotValidException exception,
            HttpServletRequest request) {

        Map<String, String> fieldErrors =
                exception.getBindingResult()
                        .getFieldErrors()
                        .stream()
                        .collect(Collectors.toMap(
                                error -> error.getField(),
                                error -> error.getDefaultMessage(),
                                (first, second) -> first
                        ));

        Map<String, Object> response = Map.of(
                "timestamp", Instant.now().toString(),
                "status", HttpStatus.BAD_REQUEST.value(),
                "error", "Validation Failed",
                "message", "One or more fields are invalid",
                "path", request.getRequestURI(),
                "fieldErrors", fieldErrors
        );

        return ResponseEntity
                .badRequest()
                .body(response);
    }
}

This validation handler can be included in the main global advice class or maintained separately. If multiple advice classes define overlapping exception handlers, their ordering and exception mappings must be configured carefully to avoid ambiguity.

10. Handling Invalid JSON and Type Mismatch Errors

Clients may submit malformed JSON or provide request parameters that cannot be converted into the expected Java type. These errors should be handled consistently.

10.1 Invalid JSON

import java.time.Instant;
import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class RequestParsingExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleInvalidBody(
            HttpMessageNotReadableException exception,
            HttpServletRequest request) {

        Map<String, Object> response = Map.of(
                "timestamp", Instant.now().toString(),
                "status", HttpStatus.BAD_REQUEST.value(),
                "error", "Bad Request",
                "message", "The request body is invalid",
                "path", request.getRequestURI()
        );

        return ResponseEntity.badRequest().body(response);
    }
}

10.2 Type Mismatch

Suppose an endpoint expects a numeric employee ID, but the client supplies a value such as abc. Spring may raise a MethodArgumentTypeMismatchException.

@ExceptionHandler(
    org.springframework.web.method.annotation
        .MethodArgumentTypeMismatchException.class
)
public ResponseEntity<String> handleTypeMismatch(
        org.springframework.web.method.annotation
                .MethodArgumentTypeMismatchException exception) {

    return ResponseEntity
            .badRequest()
            .body("A request parameter has an invalid type");
}

Place this method inside an appropriate controller advice class. It is generally preferable to return a stable, client-safe message rather than exposing internal Java type names or conversion details unnecessarily.

11. Mapping Exceptions to HTTP Status Codes

HTTP status codes communicate the result of a request to the client. Selecting the correct status helps clients determine whether to correct the request, authenticate, retry, or report a server-side problem.

Status Code Meaning Typical Scenario
400 Bad Request The request is invalid. Malformed JSON or failed validation.
401 Unauthorized Valid authentication is missing or has failed. Missing or invalid authentication credentials.
403 Forbidden The server refuses access to the resource. An authenticated user lacks permission.
404 Not Found The requested resource does not exist or is not available. Employee record not found.
405 Method Not Allowed The HTTP method is not supported for the endpoint. Using PUT on a GET-only endpoint.
409 Conflict The request conflicts with the current resource state. A duplicate registration or version conflict.
422 Unprocessable Content The content is understood but cannot be processed semantically. A domain validation failure, where this status is part of the API contract.
500 Internal Server Error An unexpected server-side failure occurred. An unhandled application error.
503 Service Unavailable The service is temporarily unable to handle the request. A temporary service outage.

Use status codes consistently and according to the API's documented behavior. Not every exception should become a 500 response; expected client errors should generally receive suitable 4xx responses.

12. Using @ResponseStatus with Custom Exceptions

The @ResponseStatus annotation can associate a custom exception with an HTTP status code.

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException
        extends RuntimeException {

    public ProductNotFoundException(String message) {
        super(message);
    }
}

This approach is convenient for straightforward cases. Use @ControllerAdvice when the application needs a consistent error-response structure, custom response fields, centralized logging, or more complex exception mapping.

13. Logging Exceptions in Global Exception Handling

Logging unexpected exceptions helps developers investigate failures. A centralized handler is a convenient place to record diagnostic information while returning a safe response to the client.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestControllerAdvice
public class ApplicationExceptionHandler {

    private static final Logger logger =
            LoggerFactory.getLogger(ApplicationExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleUnexpected(
            Exception exception) {

        logger.error("Unexpected application error",
                     exception);

        return ResponseEntity
                .internalServerError()
                .body("An unexpected error occurred");
    }
}

This is a simplified example. Add it to an appropriate advice class and ensure more specific exception handlers take precedence where necessary. Avoid logging the same exception repeatedly at every application layer unless each log adds meaningful context.

Logging Best Practices

  • Use ERROR for unexpected failures requiring investigation.
  • Use WARN for recoverable or unusual situations.
  • Include a correlation ID when available.
  • Do not expose stack traces to API clients.
  • Never log passwords, access tokens, or confidential request bodies.
  • Configure suitable log levels and retention policies.

14. Advanced Exception Handling with ProblemDetail

Spring Framework 6 and compatible Spring Boot versions support ProblemDetail for representing errors using the Problem Details format defined by RFC 9457. This provides a standardized structure for communicating API errors.

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ProblemDetailExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ProblemDetail handleNotFound(
            ResourceNotFoundException exception) {

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.NOT_FOUND,
                "The requested resource could not be found"
        );

        problem.setTitle("Resource Not Found");
        problem.setProperty("code", "RESOURCE_NOT_FOUND");

        return problem;
    }
}

When supported and configured by the Spring version in use, Spring can serialize the result as a problem-details response. This approach is useful when an API needs standardized error fields and consistent error representations across endpoints.

15. Common Problems and Troubleshooting

Problem Possible Cause Solution
Global handler is not invoked Advice class is outside component scanning or exception occurs outside the MVC handling flow. Check package scanning and identify where the exception originates.
Wrong HTTP status returned Exception is mapped to an incorrect status. Review exception-to-status mappings.
Validation errors are not handled Validation starter or DTO constraints are missing. Check dependencies, annotations, and the validation exception type.
Response format is inconsistent Handlers return different structures. Adopt a shared error-response model.
Internal details appear in responses Exception messages or stack traces are returned directly. Return safe client-facing messages and log details privately.
Handler ambiguity occurs Overlapping exception handlers or multiple advice classes conflict. Use specific mappings and review advice ordering.
Security errors bypass the advice Failure occurs in the Spring Security filter chain before controller invocation. Configure appropriate authentication entry points and access-denied handlers in Spring Security.
Unexpected exception becomes 500 No suitable specific handler exists. Add an appropriate handler for the expected exception type.

16. Testing Global Exception Handling

Testing verifies that exceptions are mapped to the expected status codes and response bodies. Spring Boot applications can use JUnit, Mockito, and MockMvc to test controller behavior and exception handling.

16.1 Example MockMvc Test

import static org.springframework.test.web.servlet.request
        .MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result
        .MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;

@WebMvcTest(EmployeeController.class)
@Import(GlobalExceptionHandler.class)
class EmployeeControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void shouldReturnNotFoundForMissingEmployee()
            throws Exception {

        mockMvc.perform(get("/api/employees/99"))
                .andExpect(status().isNotFound());
    }
}

This test assumes the controller's service dependency is provided by an appropriate test mock or test configuration, and that the service throws ResourceNotFoundException for employee ID 99. In a typical @WebMvcTest, mock the service using the mocking annotation supported by your Spring Boot version, such as @MockitoBean or, in older versions, @MockBean.

16.2 Testing Checklist

  • Test successful requests to ensure normal behavior remains unchanged.
  • Test missing resources and verify the 404 status.
  • Test malformed JSON and verify the 400 status.
  • Test invalid DTO fields and verify validation messages.
  • Test unexpected exceptions and verify a safe 500 response.
  • Verify that error responses use a consistent structure.
  • Verify that sensitive information is not included in responses.
  • Test authentication and authorization errors separately from MVC exceptions.

17. Best Practices for Global Exception Handling

  • Create a dedicated global advice class for shared exception handling.
  • Prefer @RestControllerAdvice for JSON-based REST APIs.
  • Create custom exception classes for meaningful business failures.
  • Use specific exception handlers before broad fallback handling.
  • Return correct HTTP status codes and consistent error formats.
  • Validate request data using Bean Validation.
  • Keep business logic separate from error-response formatting.
  • Log unexpected exceptions without exposing internal details to clients.
  • Use correlation IDs to help trace failures across services.
  • Handle Spring Security filter-chain errors using the appropriate security mechanisms.
  • Write automated tests for common and unexpected failure scenarios.
  • Document error codes and response structures for API consumers.

18. Practical Project: Employee Management API

Project Objective: Build a Spring Boot REST API with centralized exception handling for employee management operations.

Project Requirements

  1. Create an Employee entity and repository.
  2. Implement endpoints to create, retrieve, update, and delete employees.
  3. Create a custom ResourceNotFoundException.
  4. Implement a global exception handler using @RestControllerAdvice.
  5. Create a standardized API error-response model.
  6. Handle validation failures using @Valid and Bean Validation.
  7. Handle malformed JSON and invalid request parameters.
  8. Map exceptions to appropriate HTTP status codes.
  9. Log unexpected exceptions securely.
  10. Write MockMvc tests for success and error scenarios.

Expected Outcome

The completed application should return consistent error responses, provide clear validation feedback, handle missing resources correctly, and avoid exposing internal implementation details to clients.

19. Interview Questions and Answers

Q1. What is @ControllerAdvice?

Answer: It is a Spring annotation that allows shared controller behavior, including centralized exception handling, across multiple controllers.

Q2. What is the difference between @ControllerAdvice and @RestControllerAdvice?

Answer: @RestControllerAdvice combines controller advice with response-body behavior, making it convenient for REST APIs that return JSON or other serialized response bodies.

Q3. What is @ExceptionHandler?

Answer: It maps specific exception types to methods that handle those exceptions and generate an appropriate response.

Q4. Why is global exception handling useful?

Answer: It reduces duplicate handling logic, standardizes error responses, and makes application maintenance easier.

Q5. What is ResponseEntity?

Answer: ResponseEntity represents an HTTP response and allows developers to control its status code, headers, and body.

Q6. How do you handle resource-not-found errors?

Answer: Create a custom exception such as ResourceNotFoundException and handle it globally with an HTTP 404 response.

Q7. How do you handle validation exceptions?

Answer: Use Bean Validation annotations and handle exceptions such as MethodArgumentNotValidException to return field-specific validation errors.

Q8. What is the purpose of @ResponseStatus?

Answer: It associates an HTTP status code with a controller method or exception.

Q9. Should exception messages be returned directly to clients?

Answer: Not always. Internal exception messages can reveal implementation details. Use safe client-facing messages and keep detailed diagnostics in protected logs.

Q10. Does @ControllerAdvice handle every application error?

Answer: No. It handles exceptions that reach Spring MVC's exception-resolution mechanism. Some failures occur earlier in filters, including Spring Security filters, and require separate handling.

Q11. What is ProblemDetail?

Answer: It is a Spring representation for standardized HTTP API errors based on the Problem Details specification.

Q12. How do you test global exception handling?

Answer: Use MockMvc or integration tests to trigger exceptions and verify HTTP status codes, response fields, and safe error messages.

20. Quick Revision Checklist

  • Understand local and global exception handling.
  • Know the purpose of @ControllerAdvice and @RestControllerAdvice.
  • Use @ExceptionHandler for specific exception types.
  • Create custom exceptions for business scenarios.
  • Use ResponseEntity for explicit HTTP response control.
  • Handle request validation errors consistently.
  • Map errors to suitable HTTP status codes.
  • Protect internal exception details and sensitive information.
  • Handle Spring Security filter-chain errors separately where necessary.
  • Test normal requests and failure scenarios.

21. Conclusion

Implementing global exception handling with @ControllerAdvice is an important skill for building reliable Spring Boot applications. It allows developers to centralize error handling, return consistent API responses, manage validation failures, and separate business logic from exception-response formatting.

By combining custom exceptions, @ExceptionHandler, ResponseEntity, structured error models, secure logging, and automated tests, developers can create REST APIs that are easier to maintain, debug, and consume.


Learn More with JustAcademy

Explore the Advanced Java Training Course to strengthen your knowledge of Java, Spring Boot, REST APIs, and enterprise application development.

Register for a Course Demo to explore the available training options.

Visit the JustAcademy homepage for more courses and learning resources.

Previous Next
whatsapp